﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.IO;
using System.Threading;

namespace CnmViewer
{
    /// <summary>
    /// Interaction logic for OpenFolderDialog.xaml
    /// </summary>
    public partial class OpenFolderDialog : Window
    {
        public bool CancelReading { get; set; }
        public CnmFile[] ResultItems { get; set; }

        public OpenFolderDialog()
        {
            InitializeComponent();

            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                if (d.DriveType == DriveType.NoRootDirectory)
                    continue;

                TreeViewItem item = new TreeViewItem()
                {
                    Header = d.RootDirectory.FullName,
                    Tag = d.RootDirectory,
                };

                item.Items.Add(new TreeViewItem());
                treeDir.Items.Add(item);
            }
        }

        private void treeDir_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)e.OriginalSource;
            if (item.Items.Count == 1 && ((TreeViewItem)item.Items[0]).Tag == null)
            {
                item.Items.Clear();
                DirectoryInfo dir = (DirectoryInfo)item.Tag;

                foreach (DirectoryInfo d in dir.GetDirectories())
                {
                    TreeViewItem i = new TreeViewItem()
                        {
                            Header = d.Name,
                            Tag = d,
                        };
                    i.Items.Add(new TreeViewItem());
                    item.Items.Add(i);
                }
            }
        }

        private void cmdOK_Click(object sender, RoutedEventArgs e)
        {
            if (treeDir.SelectedItem != null)
            {
                DirectoryInfo dir = (DirectoryInfo)((TreeViewItem)treeDir.SelectedItem).Tag;

                treeDir.IsEnabled = false;
                cmdOK.IsEnabled = false;
                panelRead.Visibility = Visibility.Visible;

                Thread th = new Thread(() =>
                    {
                        try
                        {
                            List<CnmFile> result = new List<CnmFile>();
                            foreach (var file in dir.GetFiles("*.cnm"))
                            {
                                if (CancelReading)
                                    break;

                                result.Add(new CnmFile(file));
                                int i = result.Count;
                                this.Invoke(() => txtCounter.Text = i.ToString());
                            }

                            if (!CancelReading)
                            {
                                if (result.Count == 0)
                                {
                                    MessageBox.Show("В выбранном каталоге нет нужных файлов", "Нет файлов", MessageBoxButton.OK, MessageBoxImage.Stop);
                                    return;
                                }

                                var s = from cnm in result
                                        orderby cnm.Time descending
                                        select cnm;

                                ResultItems = s.ToArray();
                                this.Invoke(() => DialogResult = true);
                            }
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show(exc.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        finally
                        {
                            this.Invoke(() =>
                                {
                                    treeDir.IsEnabled = true;
                                    cmdOK.IsEnabled = true;
                                    panelRead.Visibility = Visibility.Hidden;
                                    txtCounter.Text = "0";
                                    CancelReading = false;
                                });
                        }
                    });

                th.Start();

            }
        }

        private void cmdCancel_Click(object sender, RoutedEventArgs e)
        {
            if (cmdOK.IsEnabled == false)
                CancelReading = true;
            else
                DialogResult = false;
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape && !e.IsRepeat)
            {
                cmdCancel_Click(this, e);
            }
        }

    }
}
